package util

import (
	"bytes"
	"encoding/json"
	"io"
	"io/ioutil"
	"net/http"
	"time"
)

func GetData(url string) (result interface{}, err error) {
	return _doRequest("GET", url, nil, nil)
}

func GetVmrData(url string, header map[string]string, timeout time.Duration) (result interface{}, err error) {
	return _doRequest("GET", url, nil, header, timeout)
}

func PostWithOutBody(url string) (result interface{}, err error) {
	return _doRequest("POST", url, nil, nil)
}

func PostData(url string, body interface{}) (result interface{}, err error) {
	req, err := json.Marshal(body)
	if err != nil {
		return nil, err
	}
	return _doRequest("POST", url, bytes.NewBuffer(req), nil)
}

func PutData(url string, body interface{}) (result interface{}, err error) {
	req, err := json.Marshal(body)
	if err != nil {
		return nil, err
	}
	return _doRequest("PUT", url, bytes.NewBuffer(req), nil)
}

func _doRequest(method, url string, body io.Reader, header map[string]string, timeout ...time.Duration) (result interface{}, err error) {
	client := http.DefaultClient

	if len(timeout) > 0 {
		client = &http.Client{Timeout: timeout[0], Transport: client.Transport}
	}

	req, err := http.NewRequest(method, url, body)
	if err != nil {
		return nil, err
	}

	if body != nil {
		req.Header.Set("Content-Type", "application/json")
	}
	if header != nil {
		for k, s := range header {
			req.Header.Set(k, s)
		}
	}

	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}

	defer resp.Body.Close()

	body2, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	err = json.Unmarshal(body2, &result)
	if err != nil {
		return nil, err
	}

	return result, nil
}
